<?php

namespace app\common\model;

use think\Model;
use think\Session;
use think\Config;

class Admin extends Model
{

  // 开启自动写入时间戳字段
  protected $autoWriteTimestamp = 'int';
  // 定义时间戳字段名
  protected $createTime = 'createtime';
  protected $updateTime = 'updatetime';
  protected $hidden = [
    'password',
    'salt'
  ];

  protected $append = [
    'group_text', //角色分组名称
    'avatar_text' //头像
  ];

  public static function init()
  {
    self::beforeWrite(function ($row) {
      $changed = $row->getChangedData();
      //如果修改了用户或或密码则需要重新登录
      if (isset($changed['username']) || isset($changed['password']) || isset($changed['salt'])) {
        $row->token = '';
      }
    });
  }

  public function getGroupTextAttr($value, $data)
  {
    $groupid = model('AuthGroupAccess')::where('uid', $data['id'])->value('group_id');

    if (!$groupid) {
      return null;
    }

    $name = model('AuthGroup')::where('id', $groupid)->value('name');

    return $name;
  }

  public function getAvatarTextAttr($value, $data)
  {
    //获取系统配置
    $url = config('site.url');
    $gender = !empty($data['avatar']) ? $url . $data['avatar'] : $url . '/assets/home/images/avatar.jpg';

    return $gender;
  }
}
